﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SpinUntilWinformApp1
{
    public partial class Form1 : Form
    {
        private CancellationTokenSource _ctToken = new CancellationTokenSource();
        private Test test = new Test { _flag = false };
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Task.Run(() =>
            {
                Spin(test, _ctToken.Token);
                    // BeginInvoke 与下面形成异步
                textBox1.BeginInvoke(new Action(() => { textBox1.Text = "1FINISH";
                    Thread.Sleep(1000);
                    Console.WriteLine("1");
                }));
                Console.WriteLine("2");
            });
        }


        private void Spin(Test test, CancellationToken token)
        {
            var newtoken = token;
            SpinWait.SpinUntil(() =>
            {
                return test._flag || GetCancelation(newtoken);
            });
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //test._flag = true;
             _ctToken.Cancel();
        }

        private bool GetCancelation(CancellationToken token)
        {
            return token.IsCancellationRequested;
        }
    }

    public class Test
    {
        public bool _flag;
    }

}
